package sort;

import java.util.Arrays;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-05 21:06
 **/
public class QuickSort {

    public static void main(String[] args) {
        int[] arrays = {49,38,65,97,76,13,27,49};
        //int[] arrays = {1};
        int size = arrays.length - 1;
        System.out.println("快速排序之挖坑排序升序排列前的数组:" + Arrays.toString(arrays));
        QuickSort.quickSort(arrays, 0, size);
        System.out.println("快速排序之挖坑排序升序排列后的数组:" + Arrays.toString(arrays));
        System.out.println("快速排序之挖坑排序降序排列前的数组:" + Arrays.toString(arrays));
        QuickSort.quickSort2(arrays, 0, size);
        System.out.println("快速排序之挖坑排序降序排列后的数组:" + Arrays.toString(arrays));

    }

    //降序
    public static void quickSort2(int[] arr, int low, int high) {
        if (low >= high) {
            return;
        }
        int left = low;
        int right = high;
        int pivot = arr[(low + high) / 2];

        while (left <= right) {
            while (left <= right && arr[left] > pivot) {
                left++;
            }

            while (left <= right && arr[right] < pivot) {
                right--;
            }

            if (left <= right) {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
        }
        quickSort2(arr, low, right);
        quickSort2(arr, left, high);
    }

    //升序
    public static void quickSort(int[] arr, int low, int high) {
        if (low >= high) {
            return;
        }
        int left = low;
        int right = high;
        int pivot = arr[(low + high) / 2];

        while (left <= right) {
            while (left <= right && arr[left] < pivot) {
                left++;
            }

            while (left <= right && arr[right] > pivot) {
                right--;
            }

            if (left <= right) {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
        }
        quickSort(arr, low, right);
        quickSort(arr, left, high);
    }

}
